<template>
  <pageTabelLayout :loading="pageData.loading">
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-row>
              <a-col :span="4">
                <CorporateSectorCascader
                  :configCascader="configCascader"
                  @changeCascader="changeCascader"
              /></a-col>
              <a-col :span="4">
                <a-form-item label="退坯单号" prop="tpdh">
                  <a-input
                    allow-clear
                    :style="{ width: '200px' }"
                    class="bacClass"
                    v-model="pageData.tpdh"
                  /> </a-form-item
              ></a-col>
              <a-col :span="4">
                <a-form-item label="状态" prop="state">
                  <a-select
                    allow-clear
                    :style="{ width: '200px' }"
                    class="bacClass"
                    v-model="pageData.state"
                  >
                    <a-option value="0" label="待审核">待审核</a-option>
                    <a-option value="1" label="审核通过">审核通过</a-option>
                    <a-option value="2" label="审核驳回">审核驳回</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="创建日期" prop="beginDate">
                  <a-date-picker
                    popup-container="html"
                    v-model="pageData.beginDate"
                    :style="{ width: '230px' }"
                    placeholder="选择开始日期"
                    class="bacClass"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item label="至" prop="endDate">
                  <a-date-picker
                    popup-container="html"
                    v-model="pageData.endDate"
                    :style="{ width: '240px', marginLeft: '25px' }"
                    placeholder="选择开始日期"
                    class="bacClass"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="toolbarList"
            @select="handleSelect"
            @audit="handleAduit"
            @del="handleDelete"
          >
          </Toolbar>
        </div>
      </div>

      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="gang"></div>
    </template>
    <template #pageTabel>
      <div class="w-full h-full">
        <encapsulation-agrid ref="table1Ref" :configaggrid="configaggrid"></encapsulation-agrid>
      </div>
    </template>
    <!-- 退坯入库详情 弹窗 -->
    <a-modal
      v-model:visible="returnGrayDetailModal"
      okText="关闭"
      @ok="returnGrayDetailModal = false"
      title="退坯明细"
      hideCancel
      fullscreen
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item title="汇总明细" name="1">
          <div style="width: 100%; height: 300px">
            <encapsulation-agrid
              ref="table2Ref"
              :configaggrid="configaggrid2"
            ></encapsulation-agrid>
          </div>
        </el-collapse-item>
        <el-collapse-item title="明细信息" name="2">
          <div style="width: 100%; height: 300px">
            <encapsulation-agrid
              ref="table3Ref"
              :configaggrid="configaggrid3"
            ></encapsulation-agrid>
          </div>
        </el-collapse-item>
      </el-collapse>
    </a-modal>
  </pageTabelLayout>
</template>
<script setup lang="ts">
  import { tableColumns4, tableColumns2, tableColumns3 } from './tableConfig'
  import { ref, reactive, onMounted, onUnmounted } from 'vue'
  import { post } from '@/api/http'
  import Toolbar from '@/components/Toolbar.vue'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import usePermission from '@/store/modules/permission'
  import { ElMessage } from 'element-plus'
  import dayjs from 'dayjs'
  import emitter from '@/hooks/useEventBus'
  import { Modal } from '@arco-design/web-vue'
  const today = dayjs()
  const pageData = reactive({
    loading: false,
    companyId: '',
    inShelveList: [],
    deliveryCode: '',
    state: '0',
    date: '',
    beginDate: '',
    endDate: '',
  })
  onMounted(() => {
    pageData.beginDate = today.subtract(6, 'day').format('YYYY-MM-DD')
    pageData.endDate = today.format('YYYY-MM-DD')
    emitter.on('ReturnGrayInStock-ProcessedDetailHandle', (data: any) => detailHandle(data))
  })
  onUnmounted(() => {
    emitter.off('ReturnGrayInStock-ProcessedDetailHandle', (data: any) => detailHandle(data))
  })
  const returnGrayDetailModal = ref<boolean>(false)
  const detailHandle = async (data: any) => {
    // console.log('data', data)
    returnGrayDetailModal.value = true
    try {
      //渲染汇总信息表格数据
      const res = await post({
        url: 'wms/GreyStockNewInDetail/getListTotal',
        data: {
          stockInId: data.id,
        },
      })
      if (res.code == 200) {
        nextTick(() => {
          table2Ref.value.setdataListIterface(res.data)
        })
      } else {
        ElMessage.error(res.message)
      }
      //渲染明细信息表格数据
      const result = await post({
        url: 'wms/GreyStockNewInDetail/getList',
        data: {
          stockInId: data.id,
        },
      })
      if (result.code == 200) {
        nextTick(() => {
          table3Ref.value.setdataListIterface(result.data)
        })
      } else {
        ElMessage.error(result.message)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const activeNames = ref<string[]>(['1', '2'])
  const permissionStore = usePermission()
  const toolbarList: any = ref([
    `${!permissionStore.hasPermisson('tprk.yclcx') ? '查询' : ''}`,
    `${!permissionStore.hasPermisson('tprk.yclsh') ? '审核' : ''}`,
    `${!permissionStore.hasPermisson('tprk.yclsc') ? '删除' : ''}`,
  ])
  const headerShow = ref<boolean>(true)

  const configCascader = ref<{}>({
    corporateWidth: '230px', //公司宽度
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '公司', //公司label
    cascaderShow: 'sector', //配置部门不显示
  })
  const table1Ref = ref<any>(null)
  let configaggrid = ref({
    url: 'wms/GreyStockNewIn/getPage', //接口路径
    queryData: {
      companyId: pageData.companyId,
      deliveryCode: pageData.deliveryCode,
      auditState: pageData.state,
      beginDate: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
      endDate: dayjs().format('YYYY-MM-DD'),
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns4,
    fileName: 'ReturnGrayInStock-Processed-1',
  })
  const table2Ref = ref<any>(null)
  let configaggrid2 = ref({
    url: '', //接口路径
    queryData: {},
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns2,
    fileName: 'ReturnGrayInStock-Processed-2',
  })
  const table3Ref = ref<any>(null)
  let configaggrid3 = ref({
    url: '', //接口路径
    queryData: {},
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns3,
    fileName: 'ReturnGrayInStock-Processed-3',
  })
  const handleSelect = () => {
    try {
      pageData.loading = true
      table1Ref.value.setQuery({
        companyId: pageData.companyId,
        deliveryCode: pageData.deliveryCode,
        auditState: pageData.state,
        beginDate: pageData.beginDate,
        endDate: pageData.endDate,
      })
    } catch (e) {
      console.log(e)
    } finally {
      pageData.loading = false
    }
  }
  const focusShelve = async () => {
    try {
      pageData.loading = true
      let { code, data, message } = await post({
        url: 'wms/warehouse/getWarehouseByPara',
        data: { firmId: pageData.companyId, warehouseTypeName: '坯布仓', virtuallyState: 0 },
      })
      if (code == 200) {
        pageData.inShelveList = data
        pageData.loading = false
        return
      }
      ElMessage.error(message)
    } finally {
      pageData.loading = false
    }
  }
  const changeCascader = (data: any) => {
    const { corporateId, corporateLabel } = data
    pageData.companyId = corporateId
    focusShelve()
  }
  //审核
  const handleAduit = async () => {
    if (!table1Ref.value.getSelectedRows().length) {
      ElMessage.error('请选择要审核的数据')
      return
    }
    try {
      pageData.loading = true
      const res = await post({
        url: 'wms/GreyStockNewIn/setAudit',
        data: {
          ids: table1Ref.value.getSelectedRows().map((item: any) => item.id),
          auditState: 1,
        },
      })
      if (res.code == 200) {
        ElMessage.success(res.message)
        handleSelect()
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      console.log(e)
    } finally {
      pageData.loading = false
    }
  }
  //删除
  const handleDelete = () => {
    if (!table1Ref.value.getSelectedRows().length) {
      ElMessage.error('请选择要删除的数据！')
      return
    }
    if (table1Ref.value.getSelectedRows().some((item: any) => item.auditState == 1)) {
      ElMessage.error('审核通过的数据不能进行删除操作！')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      async onOk() {
        try {
          pageData.loading = true
          const res = await post({
            url: 'wms/GreyStockNewIn/delete',
            data: table1Ref.value.getSelectedRows().map((item: any) => item.id),
          })
          if (res.code == 200) {
            ElMessage.success(res.message)
            handleSelect()
          } else {
            ElMessage.error(res.message)
          }
        } catch (e) {
          console.log(e)
        } finally {
          pageData.loading = false
        }
      },
    })
  }
</script>

<style scoped>
  :deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  :deep(.arco-picker input) {
    padding-left: 0 !important;
  }
  :deep(.arco-picker) {
    padding-left: 0 !important;
  }
  :deep(.arco-picker-separator) {
    padding: 0 !important;
  }
</style>
<style>
  .el-scrollbar__view {
    height: 100%;
  }
  .el-collapse {
    border-top: 0;
  }
</style>
